<template>
    <Tabs type="card">
        <TabPane label="用电统计">
            <Card class="no-border-card">
                <!--标题-->
                <p slot="title">
                    用电统计
                    <Button type="primary" class="btn-in-top-large" @click="handleDownload" v-pmis="36">导出报表</Button>
                </p>
                <!--标题end-->

                <!--搜索条件-->
                <Row :gutter="8" align="middle" style="margin-bottom:15px">
                    <Col span="5">
                        <!-- 门店选择 -->
                        <Select
                            v-model="searchData.branch_id"
                            filterable
                            placeholder="选择门店"
                            @on-change="areaChange">
                            <Option v-for="item in areaList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                        </Select>
                    </Col>

                    <!-- 房源选择 -->
                    <Col span="5">
                        <Select v-model="searchData.home_ids" multiple filterable placeholder="选择房源">
                            <Option v-for="item in houseList" :value="item.id" :key="item.id">{{ item.home_name }}</Option>
                        </Select>
                    </Col>

                    <!-- 付费模式选择 -->
                    <Col span="5">
                        <Select v-model="searchData.pay_type" placeholder="付费模式">
                            <Option v-for="item in payTypeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                        </Select>
                    </Col>

                    <Col span="7">
                        <DatePicker
                            :clearable="false"
                            style="width:100%;"
                            type="daterange"
                            placeholder="统计时间段"
                            v-model="searchData.timeRange">
                        </DatePicker>
                    </Col>

                    <Col span="2">
                        <Button type="primary" icon="ios-search-strong" style="padding:4px 0px 3px;" @click="handleSearch"></Button>
                    </Col>
                </Row>
                <!--搜索条件end-->

                <!--用电统计表格数据-->
                <Table stripe border :columns="columns" :data="datas" :loading="isLoadig"></Table>
                <!--用电统计表格数据end-->


                <!--分页-->
                <Page
                :total="total"
                :page-size="searchData.limit"
                :current.sync="currentPage"
                @on-change="handlePageChange"
                show-elevator
                show-total
                style="text-align:center"></Page>
                <!--分页end-->

                <!-- 选择弹窗 -->
                <Modal
                    v-model="isModalVisible"
                    class-name="vertical-center-modal"
                    :closable="false"
                    :mask-closable="false"
                    title="请选择需要核查的房源"
                    width="570">

                    <Form :label-width="80" style="margin-top:20px;padding-right:10px">

                        <FormItem label="门店">
                            <Select
                                v-model="searchData.branch_id"
                                filterable
                                placeholder="选择门店"
                                @on-change="areaChange">
                                <Option v-for="item in areaList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                            </Select>
                        </FormItem>

                        <FormItem label="房源">
                            <Select v-model="searchData.home_ids" multiple filterable placeholder="选择房源">
                                <Option v-for="item in houseList" :value="item.id" :key="item.id">{{ item.home_name }}</Option>
                            </Select>
                        </FormItem>

                        <FormItem label="付费模式">
                            <Select v-model="searchData.pay_type" placeholder="付费模式">
                                <Option v-for="item in payTypeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                            </Select>
                        </FormItem>

                        <FormItem label="统计时间">
                            <DatePicker
                                :clearable="false"
                                style="width:100%;"
                                type="daterange"
                                placeholder="统计时间段"
                                v-model="searchData.timeRange">
                            </DatePicker>
                        </FormItem>

                    </Form>

                    <div slot="footer" style="padding:10px 0">
                        <Button @click="closeModal">关闭</Button>
                        <Button
                            type="primary"
                            :loading="getLoading"
                            @click="handleSearch">确定</Button>
                    </div>
                </Modal>

            </Card>
        </TabPane>
    </Tabs>
</template>

<script>
import omit from 'lodash/omit'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
import { date, searchTimeRange, timeRangeDifference, now, twoDaysAgo } from '@/libs/date'

export default {
  name: 'electriCount',
  data () {
    return {
      isModalVisible: true,
      areaList: [], // 门店列表
      houseList: [], // 房源列表
      payTypeList: [{ id: 1, name: '预付费' }, { id: 2, name: '后付费' }, { id: 3, name: '不限' }], // 付费模式列表
      searchData: {
        // 搜索条件
        timeRange: [ twoDaysAgo, now ],
        limit: 30, // 每页数据量
        offset: 0, // 分页查询时跳过条数
        branch_id: '', // 门店id
        home_ids: [], // 房源id || 'all'
        pay_type: 3, // 付费模式
        start_time: '', // 统计时间，开始时间
        end_time: '', // 统计时间，结束时间
        download: false // 是否导出，默认false
      },
      getLoading: false,
      isLoadig: false, // 表格loading状态
      columns: [
        {
          width: 160,
          title: '统计时间',
          key: 'time',
          align: 'center'
        },
        {
          minWidth: 90,
          title: '所属门店',
          key: 'area',
          align: 'center'
        },
        {
          minWidth: 200,
          title: '详细地址',
          key: 'address',
          align: 'center'
        },
        {
          minWidth: 90,
          title: '房间号',
          key: 'house',
          align: 'center'
        },
        {
          minWidth: 90,
          title: '租客',
          key: 'tenant',
          align: 'center'
        },
        {
          minWidth: 90,
          title: '付费模式',
          key: 'payType',
          align: 'center'
        },
        {
          minWidth: 90,
          title: '房间用电量',
          key: 'electricUser',
          align: 'center'
        },
        {
          minWidth: 90,
          title: '公摊用电量',
          key: 'electricPublic',
          align: 'center'
        },
        {
          minWidth: 90,
          title: '总用电量',
          key: 'electriAll',
          align: 'center'
        },
        {
          minWidth: 140,
          title: '备注',
          key: 'tip',
          align: 'center'
        }
      ],
      datas: [], // 表格数据
      total: 0, // 总数据量
      currentPage: 1 // 当前页码
    }
  },
  mounted () {
    this.getAreaList() // 获取门店列表
  },
  computed: {
    userHasBranchs () {
      const { branches } = this.$store.state.user
      return !!branches.length
    }
  },
  methods: {
    getQuery (download = false) {
      const { currentPage } = this
      const { limit, branch_id, home_ids, pay_type, timeRange } = this.searchData
      const [ start_time, end_time ] = searchTimeRange(timeRange)
      if (
        (!branch_id && branch_id !== 0) ||
                home_ids.length === 0 ||
                pay_type.length === 0
      ) {
        this.$Message.warning('请完整选择信息')
        return false
      }
      if (timeRangeDifference(start_time, end_time, 90)) {
        this.$Message.warning('查询时间区间不能超过90天')
        return false
      }
      const params = {
        start_time,
        end_time,
        branch_id,
        pay_type,
        home_ids: home_ids.includes('all') ? 'all' : JSON.stringify(home_ids)
      }
      if (download) {
        params.download = true
      } else {
        params.limit = limit
        params.offset = (currentPage - 1) * limit
      }
      return params
    },
    handleDownload () {
      const query = this.getQuery(true)
      if (query === false) return
      this.exportTable(query)
    },
    handleSearch () {
      this.currentPage = 1
      this.fetchRecord(true)
    },
    handlePageChange () {
      this.fetchRecord()
    },
    async fetchRecord (recount = false) {
      try {
        this.isModalVisible = false
        this.isLoadig = true
        const query = this.getQuery()
        if (query === false) return
        if (recount) this.fetchRecordCount(query)
        const res = await http.req(api.electric_report, null, query)
        this.datas = this.handleData(res.rooms, query.branch_id, query.start_time, query.end_time)
      } catch (err) {
        console.log(err)
      } finally {
        this.isLoadig = false
      }
    },
    async fetchRecordCount (params) {
      try {
        const query = omit(params, [ 'limit', 'offset' ])
        const res = await http.req(api.electric_report_count, null, query)
        if (res) this.total = res.count
      } catch (err) {
        console.log(err)
      }
    },
    // 获取门店列表
    getAreaList () {
      dataCenter.getStores(this, res => {
        if (res) {
          this.areaList = res
          if (!this.userHasBranchs) {
            this.areaList.unshift({ name: '总部', id: 0 })
          }
          this.searchData.branch_id = this.areaList[0].id
          this.areaChange()
        }
      })
    },
    areaChange () {
      this.houseList = []
      this.searchData.home_ids = []
      this.getHouseList()
    },
    // 获取房源列表
    getHouseList () {
      http.request(this, api.home_list, null, { branch_id: this.searchData.branch_id, limit: 50 }, (res, err) => {
        // console.log('对应房源列表', res);
        this.houseList = res && res.homes
        this.houseList.unshift({ id: 'all', home_name: '不限' })
        this.searchData.home_ids = this.houseList[0].id
      })
    },

    handleData (data, branch_id, start_time, end_time) {
      const res = []
      const time = `${date(start_time, 'YYYY-MM-DD HH:mm')} 至 ${date(end_time, 'YYYY-MM-DD HH:mm')}`
      const branch = this.areaList.find(branch => branch.id === branch_id)
      const payTypeArr = ['', '预付费', '后付费']

      for (let key in data) {
        const tenant = data[key].leases && data[key].leases[0] && data[key].leases[0].tenant
        let item = {
          time: time,
          area: (branch && branch.name) || '',
          address: data[key].detail_address,
          house: data[key].room_name,
          tenant: typeof tenant === 'object' ? `${tenant.name} - ${tenant.phone}` : '暂无租客',
          payType: data[key].elemeter_setting_info && payTypeArr[data[key].elemeter_setting_info.pay_type],
          electricUser: data[key].room_consume || '-',
          electricPublic: data[key].pool_consume || '-',
          electriAll: data[key].total_consume || '-',
          tip: data[key].remark
        }
        res.push(item)
      }
      return res
    },
    // 导出报表
    exportTable (param) {
      // 导出报表
      http.exportTable(this, api.electric_report, null, param)
    },
    closeModal () {
      this.isModalVisible = false
    }
  }
}
</script>

<style lang="less">
.export-link {
    color: #fff;
    text-decoration: none;
}
.export-link:hover {
    color: #fff;
}
</style>